import { logger } from './logger';
import access from '@ohos.bluetooth.access';
import promptAction from "@ohos.promptAction";
import connection from '@ohos.bluetooth.connection';
import { chartOptions } from '../models/chartOptions';

export function getDevices() {
  return connection.getPairedDevices();
}

export function getMac() {
  try {
    return access.getLocalAddress();
  } catch (err) {
    logger.instance.error(err);
    this.showPopup('请检查蓝牙状态！');
    return '';
  }
}

export function getTime() {
  const dt = new Date();
  return dt.getTime();
}

export function isEmpty(obj: Object): boolean {
  return typeof obj == "undefined" || obj == null || obj?.toString().trim() == "";
}

export function showPopup(msg: string, duration?: number) {
  if (isEmpty(duration))
    duration = 2000;
  promptAction.showToast({
    message: msg,
    duration: duration,
  });
}

export function assembleAndCountValueRanges(values: number[]) {
  let valueCounts: { [key: string]: number } = {};
  for (const temp of values) {
    const value = Math.floor(temp * 2) / 2;
    if (valueCounts.hasOwnProperty(value.toString()))
      valueCounts[value.toString()]++;
    else
      valueCounts[value.toString()] = 1;
  }
  const options = new chartOptions();
  for (const value in valueCounts) {
    if (valueCounts.hasOwnProperty(value)) {
      options.xAxisData.push(Number(value));
      options.seriesData.push(valueCounts[value]);
    }
  }
  return options;
}